import { login, getUserInfo } from '@/api/user'
import { setToken, getToken } from '@/libs/util'
import md5 from 'js-md5'
import config from '@/config'
import moment from 'moment'
export default {
  state: {
    severUserInfo: {},
    loginAccount: '',
    token: getToken()
  },
  getters: {
    userInfo: state => state.severUserInfo
  },
  mutations: {
    setSeverUserInfo (state, severUserInfo) {
      state.severUserInfo = severUserInfo
    },
    setLoginAccount (state, data) {
      state.loginAccount = data
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    }
  },
  actions: {
    handleLogin ({ commit }, { userName, password }) {
      userName = userName.trim()
      password = md5(config.pwdPrefix + password)
      let timestamp = moment.utc().valueOf()
      let sign = md5('' + timestamp).toUpperCase()
      return new Promise((resolve, reject) => {
        login({
          userName,
          password,
          timestamp,
          sign
        }).then(res => {
          const data = res.data
          if (data.r !== false) {
            commit('setToken', data.token)
            commit('setSeverUserInfo', data)
          }
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    jiaLogin ({ commit }, { userName, password }) {
      commit('setToken', '3334455667788')
    },
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        // logout().then(() => {
        //  commit('setToken', '')
        //  commit('setAccess', [])
        //  resolve()
        // }).catch(err => {
        //  reject(err)
        // })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        commit('setToken', '')
        resolve()
      })
    },
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(res => {
            const data = res.data
            commit('setSeverUserInfo', data)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    setLoginAccount ({ state, commit }, data) {
      commit('setLoginAccount', data)
    }
  }
}
